package base.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 非阻塞客户端
 *
 * Author: shen qi han
 * Date: 2022/4/10 上午12:25
 */
public class MyNioClient {


    public MyNioClient() throws IOException {
    }

    static boolean NOT_NIO = false;

    static String CLIENT_IP = "127.0.0.1";

    static int SERVER_PORT = 6688;

    SocketChannel socketChannel = SocketChannel.open();

    public void init() throws IOException {
        socketChannel.configureBlocking(NOT_NIO);
        InetSocketAddress targetAddr = new InetSocketAddress(SERVER_PORT);
        // connect server
        if(!socketChannel.connect(targetAddr)){
            while(!socketChannel.finishConnect()){
                System.out.println("connecting....");
            }
        }
    }

    public void send(String msg) throws IOException {
        // send msg
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        socketChannel.write(buffer);
    }

    public static void main(String[] args) throws IOException {
        Scanner cin = new Scanner(System.in);
        String exit = "exit";
        String msg = "";

        MyNioClient client = new MyNioClient();
        client.init();

        while(!exit.equals((msg = cin.next()))){
            if(!"".equals(msg)){
                // send msg
                client.send(msg);
                System.out.println("send. " + msg);
            }
        }

    }

}
